package com.gzxx.util.excelutil;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author Pengpdx
 * @description: EasyExcel写工具类
 * @date 2020/9/21 18:30
 */
public class EasyExcelWriteUtil {


    /**
     * 文件下载
     * @param response      HttpServletResponse
     * @param fileName      导出的文件名
     * @param sheetName     导入文件的 sheet 名
     * @param list          数据 list
     * @param cls           映射实体类，Excel 模型
     * @throws IOException
     */
    public static void writeExcel(HttpServletResponse response, String fileName, String sheetName,
                                  List<?> list, Class<?> cls){
        OutputStream outputStream = getOutputStream(fileName, response);
        ExcelWriter excelWriter = EasyExcel.write(outputStream, cls).build();
        WriteSheet writeSheet = EasyExcel.writerSheet(sheetName).build();
        excelWriter.write(list, writeSheet);
        excelWriter.finish();
    }


    /**
     * 导出文件时为Writer生成OutputStream
     */
    private static OutputStream getOutputStream(String fileName, HttpServletResponse response) {
        //创建本地文件
        try {
            response.setCharacterEncoding("utf-8");
            fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");

            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ExcelTypeEnum.XLSX.getValue());
            return response.getOutputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
